import 'dart:io';

import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'package:image_editor/image_editor.dart';
import 'package:extended_image/src/extended_image_utils.dart';
import 'package:extended_image/src/editor/extended_image_editor_utils.dart';
import 'package:extended_image/src/editor/extended_image_editor.dart';
import 'package:extended_image/src/extended_image.dart';
import 'package:photo_preview/photo_preview_export.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';









/// @author: pengboboer
/// @createDate: 4/25/21
///裁剪页面
class ClipImageHeadBorderPage extends StatefulWidget {
  //左取消组件
  final Widget topLeftWidget;
  //背景颜色
  final Color backgroundColor;
  //蒙版颜色
  final Color maskColor;
  //取景框配置
  final EditorConfig editorConfig;
  //取景框比例
  final double aspectRatio;
  //取景框线宽
  final double lineWidth;
  //取景框线颜色
  final Color lineColor;
  //边距值
  final double marginValue;
  //左取消组件
  final Widget leftCancelWidget;
  //右裁剪组件
  final Widget rightClipWidget;
  // 是否显示头像描边框
  final bool isShowHeadBorderWidget;

  final String url;
  // 是否显示文字提示
  final bool isShowTextPrompt;

  const ClipImageHeadBorderPage(
      {Key key,
        this.topLeftWidget,
        this.backgroundColor,
        this.maskColor,
        this.editorConfig,
        this.aspectRatio,
        this.lineWidth,
        this.lineColor,
        this.marginValue,
        this.leftCancelWidget,
        this.rightClipWidget,
        this.isShowHeadBorderWidget, this.url, this.isShowTextPrompt})
      : assert(url != null && url != "", "url cannot be empty"), super(key: key);

  @override
  State createState() => ClipImageHeadBorderState();
}



///裁剪
class ClipImageHeadBorderState extends State<ClipImageHeadBorderPage> {
  GlobalKey<ExtendedImageEditorState> editorKey = GlobalKey<ExtendedImageEditorState>();

  String _url;

  @override
  void initState() {
    super.initState();
    _url = widget?.url;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: widget?.backgroundColor ?? Colors.black,
      body: Container(
        child: Stack(
          children: <Widget>[
            _buildMainWidget(),
            _buildHintAndConfirmWidget(),
            // _buildLeftTextWidget(),
            // _buildRightTextWidget(),
            _buildTopLeftWidget()
          ],
        ),
      ),
    );
  }

  Widget _buildMainWidget() {
    if (VgStringUtils.isNetUrl(_url)) {
      return _buildNetWorkMainWidget();
    }
    return _buildFileMainWidget();
  }

  Widget _buildNetWorkMainWidget() {
    return ExtendedImage.network(
      _url,
      fit: BoxFit.contain,
      extendedImageEditorKey: editorKey,
      mode: ExtendedImageMode.editor,
      initEditorConfigHandler: (state) {
        return widget?.editorConfig ??
            EditorConfig(
                maxScale: 8.0,
                cropRectPadding: EdgeInsets.all(widget?.marginValue ?? 30),
                cornerSize: Size(18, -2.5),
                cornerColor: Colors.white,
                lineColor: widget?.lineColor ?? Colors.white,
                lineHeight: widget?.lineWidth ?? 1,
                editorMaskColorHandler: (context, bo) {
                  return widget?.maskColor ?? Color(0x80000000);
                },
                hitTestSize: 0,
                initCropRectType: InitCropRectType.layoutRect,
                cropAspectRatio: widget?.aspectRatio,
                maskWidget: (widget.isShowHeadBorderWidget ?? false) ? Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Container(
                        width: ScreenUtils.screenW(context) - 60,
                        height: ScreenUtils.screenW(context) - 60,
                        child: Container(
                            color: Colors.black.withOpacity(0.1),
                            child: Image.asset("images/head_border.png")
                        )
                    ),
                  ],
                ) : Container()
            );
      },
    );
  }

  Widget _buildFileMainWidget() {
    return ExtendedImage.file(
      File(_url),
      fit: BoxFit.contain,
      extendedImageEditorKey: editorKey,
      mode: ExtendedImageMode.editor,
      initEditorConfigHandler: (state) {
        return widget?.editorConfig ??
            EditorConfig(
                maxScale: 8.0,
                cropRectPadding: EdgeInsets.all(widget?.marginValue ?? 30),
                cornerSize: Size(18, -2.5),
                cornerColor: Colors.white,
                lineColor: widget?.lineColor ?? Colors.white,
                lineHeight: widget?.lineWidth ?? 1,
                editorMaskColorHandler: (context, bo) {
                  return widget?.maskColor ?? Color(0x80000000);
                },
                hitTestSize: 0,
                initCropRectType: InitCropRectType.layoutRect,
                cropAspectRatio: widget?.aspectRatio,
                maskWidget: (widget.isShowHeadBorderWidget ?? false) ? Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Container(
                        width: ScreenUtils.screenW(context) - 60,
                        height: ScreenUtils.screenW(context) - 60,
                        child: Container(
                            color: Colors.black.withOpacity(0.1),
                            child: Image.asset("images/head_border.png")
                        )
                    ),
                  ],
                ) : Container()
            );
      },
    );
  }

  Widget _buildHintAndConfirmWidget() {
    return Positioned(
      top: (ScreenUtils.screenH(context) - ScreenUtils.getBottomBarH(context) - ScreenUtils.getStatusBarH(context)) / 2 + ScreenUtils.screenW(context) / 2,
      child: Container(
        margin: EdgeInsets.only(top: 10),
        width: ScreenUtils.screenW(context),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            // Text(
            //   "请尽量放大头像并保持清晰",
            //   style: TextStyle(
            //       fontSize: 12,
            //       color: Color(0xffffb714)
            //   )
            // ),
            Container(
              child: (widget?.isShowTextPrompt != false) ?
              Text(
                "请尽量放大头像并保持清晰",
                style: TextStyle(
                    fontSize: 12,
                    color: Color(0xffffb714)
                )
              )
                  : Text(""),
            ),
            SizedBox(
              height: 40,
            ),
            Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                _buildLeftTextWidget(),
                SizedBox(width: 30),
                _buildRightTextWidget()
              ],
            )
          ],
        ),
      ),
    );
  }

  Widget _buildLeftTextWidget() {
    return  GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () => Navigator.of(context).pop(),
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(25)),
          color: Colors.white.withOpacity(0.2)
        ),
        width: 130,
        height: 40,
        alignment: Alignment.center,
        child: widget?.leftCancelWidget ??
            Text(
              "取消",
              style: TextStyle(color: Colors.white, fontSize: 15, height: Platform.isIOS ? 1.2 : 1.15),
            ),
      ),
    );
  }

  Widget _buildRightTextWidget() {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        managerClipData();
      },
      child: Container(
        decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(25)),
            color: ThemeRepository.getInstance()?.getPrimaryColor_1890FF()
        ),
        width: 130,
        height: 40,
        alignment: Alignment.center,
        child: widget?.rightClipWidget ??
            Text(
              "确定",
              style: TextStyle(color: Colors.white, fontSize: 15, height: Platform.isIOS ? 1.2 : 1.15),
            ),
      ),
    );
  }

  Widget _buildTopLeftWidget() {
    return Positioned(
      top: ScreenUtils.getStatusBarH(context),
      left: 0,
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          Navigator.of(context).pop("");
        },
        child: Container(
          child: widget?.topLeftWidget ??
              _topLeftWidget(),
        ),
      ),
    );
  }

  Widget _topLeftWidget(){
    return ClickAnimateWidget(
      child: Container(
        width: 40,
        height: 44,
        alignment: Alignment.centerLeft,
        padding: const EdgeInsets.only(left: 15.6),
        child: Image.asset(
          "images/top_bar_back_ico.png",
          width: 9,
          color: Color(0xFF5E687C),
        ),
      ),
      scale: 1.4,
      onClick: () {
        // VgNavigatorUtils.pop(context);
        FocusScope.of(context).requestFocus(FocusNode());
        Navigator.of(context).maybePop();
      },
    );
  }

  ///处理裁剪数据
  void managerClipData() async {
    final ExtendedImageEditorState state = editorKey?.currentState;
    if (state == null) {
      print("裁剪失败");
      return;
    }
    final EditActionDetails editAction = state.editAction;

    final Rect cropRect = state.getCropRect();
    final img = state.rawImageData;
    final rotateAngle = editAction.rotateAngle.toInt();
    final flipHorizontal = editAction.flipY;
    final flipVertical = editAction.flipX;
    ImageEditorOption option = ImageEditorOption();

    if (editAction.needCrop) {
      option.addOption(ClipOption.fromRect(cropRect));
    }

    if (editAction.needFlip) {
      option.addOption(
          FlipOption(horizontal: flipHorizontal, vertical: flipVertical));
    }

    if (editAction.hasRotateAngle) {
      option.addOption(RotateOption(rotateAngle));
    }
    final result = await ImageEditor.editImageAndGetFile(
      image: img,
      imageEditorOption: option,
    );
    print("zxx:-----裁剪图片路径：${result?.path}");
    Navigator.of(context).pop(result?.path);
  }

  @override
  void dispose() {
    editorKey = null;
    super.dispose();
  }
}